<template>
  <div class="fishing-circle-container">

    <!-- 视图切换控制 - 固定在视窗右上角 -->
    <div v-if="!loading || circles.length > 0" class="view-controls">
      <button class="toggle-btn single-toggle" @click="toggleViewMode">
        <span class="icon"> 🗺️</span>
        地图模式
      </button>
    </div>

    <!-- 内容区域 - 可滚动 -->
    <div class="fishing-circle-content scrollable">
      <!-- 加载状态 -->
      <div v-if="loading && circles.length === 0" class="loading-container">
        <div class="loading-spinner"></div>
        <p>正在加载钓点圈信息...</p>
      </div>

      <!-- 错误状态 -->
      <div v-else-if="error" class="error-container">
        <div class="error-icon">⚠️</div>
        <p>{{ error }}</p>
        <button @click="loadData" class="retry-btn">重试</button>
      </div>

      <!-- 空数据状态 -->
      <div v-else-if="!loading && circles.length === 0" class="empty-container">
        <div class="empty-icon">🎯</div>
        <h3>暂无钓点圈</h3>
        <p>还没有创建任何钓点圈，快来创建第一个吧！</p>
      </div>

      <!-- 网格布局 -->
      <div v-else class="cards-grid">
        <div v-for="circle in circles" :key="circle.id" class="circle-card" @click="openDetail(circle)">
          <div class="card-image">
            <img :src="getFirstImage(circle.pics)" :alt="circle.title" @error="handleImageError" />
            <div class="card-overlay">
              <div class="status-badge" :class="{ active: circle.isActive }">
                {{ circle.isActive ? '启用' : '未启用' }}
              </div>
              <h3 class="card-title">{{ circle.title }}</h3>
              <p class="card-city">{{ circle.city || '未知地区' }}</p>
            </div>
          </div>
        </div>
      </div>


      <!-- 加载状态提示 -->
      <div v-if="loading && circles.length > 0" class="loading-more">
        <div class="loading-spinner small"></div>
        <span>{{ circles.length >= 40 ? '正在加载最后几条数据...' : '正在加载更多数据...' }}</span>
      </div>

      <!-- 加载更多提示（仅在非加载状态且有更多数据时显示） -->
      <div v-if="!loading && hasMore && circles.length > 0" class="scroll-trigger" @click="loadMore"
        style="cursor: pointer;">
        <div class="loading-more">
          <div class="loading-spinner small"></div>
          <span>{{ circles.length >= 40 ? '点击加载更多钓点圈' : '向下滚动加载更多钓点圈' }}</span>
        </div>
      </div>

      <!-- 加载完成提示 -->
      <div v-if="!loading && !hasMore && circles.length > 0" class="end-message">
        <p>🎯 已加载全部 {{ circles.length }} 个钓点圈</p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { invoke } from '@tauri-apps/api/core'

// 类型定义
interface Location {
  latitude: number
  longitude: number
}

interface FishingCircle {
  id: string
  title: string
  description: string
  area: string
  latitude: number
  longitude: number
  points: Location[]
  city: string
  cityCode: string
  isActive: boolean
  pics: string[]
}

interface ApiResponse {
  records: FishingCircle[]
  total: number
  size: number
  current: number
  pages: number
}

// 路由
const router = useRouter()
const route = useRoute()

// 状态管理
const circles = ref<FishingCircle[]>([])
const loading = ref(false)
const error = ref('')
const currentPage = ref(1)
const hasMore = ref(true)
const pageSize = 12 // 每页显示12个
const searchQuery = ref('') // 搜索查询

// 获取第一张图片作为卡片背景
const getFirstImage = (pics: string[]): string => {
  if (!pics || pics.length === 0) {
    return '/placeholder-fishing.jpg'
  }
  return pics[0]
}

// 处理图片加载失败
const handleImageError = (event: Event) => {
  //TODO: 处理图片加载失败
}

// 调用后端API获取钓点圈列表
const fetchCircles = async (pageNum: number): Promise<ApiResponse> => {
  try {
    const response = await invoke('get_fishing_circles', {
      page: pageNum,
      size: pageSize
    })

    return response as ApiResponse
  } catch (err) {
    console.error('获取钓点圈失败:', err)
    throw new Error('获取钓点圈失败')
  }
}

// 加载数据
const loadData = async () => {
  try {
    loading.value = true
    error.value = ''

    const response = await fetchCircles(currentPage.value)
    circles.value = response.records

    // 判断是否还有更多数据
    hasMore.value = currentPage.value < response.pages

  } catch (err) {
    error.value = err instanceof Error ? err.message : '加载失败，请重试'
    console.error('加载数据失败:', err)
  } finally {
    loading.value = false
  }
}

// 滚动加载状态
let isLoadingMore = false

// 加载更多
const loadMore = async () => {
  console.log('📥 loadMore 被调用')
  console.log('loading:', loading.value)
  console.log('hasMore:', hasMore.value)
  console.log('isLoadingMore:', isLoadingMore)

  if (loading.value || !hasMore.value || isLoadingMore) {
    console.log('❌ loadMore 被阻止 - 条件不满足')
    return
  }

  isLoadingMore = true
  console.log('🔄 开始加载更多数据...')

  try {
    currentPage.value++
    console.log('加载第', currentPage.value, '页')

    const response = await fetchCircles(currentPage.value)
    circles.value.push(...response.records)

    // 更新是否还有更多数据
    hasMore.value = currentPage.value < response.pages
    console.log('加载完成，总数据量：', circles.value.length)

  } catch (err) {
    console.error('❌ 加载更多失败:', err)
    error.value = '加载更多失败'
    currentPage.value-- // 回滚页码
  } finally {
    isLoadingMore = false
    console.log('🏁 loadMore 完成')
  }
}

// 检查是否需要加载更多
const checkLoadMore = () => {
  console.log('=== 🔍 滚动检查开始 ===')
  console.log('📊 状态检查:')
  console.log('  loading:', loading.value)
  console.log('  hasMore:', hasMore.value)
  console.log('  isLoadingMore:', isLoadingMore)
  console.log('  circles数量:', circles.value.length)

  if (loading.value || !hasMore.value || isLoadingMore) {
    console.log('❌ 跳过加载 - 状态不满足')
    return
  }

  const container = getScrollContainer()
  
  // 计算滚动位置
  const scrollTop = container === document.body ? window.pageYOffset : (container as HTMLElement).scrollTop
  const scrollHeight = container === document.body ? document.documentElement.scrollHeight : (container as HTMLElement).scrollHeight
  const clientHeight = container === document.body ? window.innerHeight : (container as HTMLElement).clientHeight

  // 检查是否接近底部（距离底部300px内）
  const threshold = 300
  const shouldLoadMore = scrollHeight - scrollTop - clientHeight < threshold

  if (shouldLoadMore) {
    console.log('触发加载更多')
    loadMore()
  } else {
    console.log('⏳ 不满足触发条件')
  }
  console.log('=== 🔍 检查结束 ===\n')
}

// 防抖函数
const debounce = <T extends (...args: any[]) => void>(
  func: T,
  wait: number
): ((...args: Parameters<T>) => void) => {
  let timeout: ReturnType<typeof setTimeout>
  return (...args: Parameters<T>) => {
    clearTimeout(timeout)
    timeout = setTimeout(() => func(...args), wait)
  }
}

// 防抖处理函数
const debouncedCheckLoadMore = debounce(() => {
  console.log('🔄 滚动事件触发')
  checkLoadMore()
}, 100)

// 获取滚动容器 - 始终使用fishing-circle-content
const getScrollContainer = (): HTMLElement => {
  const container = document.querySelector('.fishing-circle-content') as HTMLElement
  return container || document.body as HTMLElement
}

// 搜索处理
const handleSearch = (query: string) => {
  console.log('🔍 收到搜索请求:', query)
  searchQuery.value = query

  // 重置数据并重新加载
  circles.value = []
  currentPage.value = 1
  hasMore.value = true
  loadData()
}

// 监听全局搜索事件
const handleGlobalSearch = (event: Event) => {
  const customEvent = event as CustomEvent
  const { query } = customEvent.detail
  handleSearch(query)
}

// 打开详情
const openDetail = (circle: FishingCircle) => {
  console.log('打开钓点圈详情:', circle.title, 'ID:', circle.id)
  // 使用路由跳转到详情页面，保留当前mode参数
  router.push({
    path: `/circle-detail/${circle.id}`,
    query: { ...route.query }
  })
}

// 切换视图模式
const toggleViewMode = () => {
  const event = new CustomEvent('toggle-map-mode', {
    detail: { isMapMode: true, modeHandler: 'FishingCircle' }

  })
  window.dispatchEvent(event)
  console.log('钓点圈页面切换到地图模式，事件已发送')
}

// 清理函数 - 清理fishing-circle-content和body
const cleanupListeners = () => {
  console.log('🧹 清理监听器...')
  window.removeEventListener('global-search', handleGlobalSearch as EventListener)

  const container = document.querySelector('.fishing-circle-content') as HTMLElement
  if (container) {
    container.removeEventListener('scroll', debouncedCheckLoadMore as EventListener)
  }
  document.body.removeEventListener('scroll', debouncedCheckLoadMore as EventListener)
  console.log('✅ 监听器已清理')
}

onMounted(async () => {
  console.log('🚀 组件挂载，开始初始化...')

  window.addEventListener('global-search', handleGlobalSearch as EventListener)

  await loadData()

  console.log('📡 添加滚动监听器...')
  
  // 延迟添加滚动监听器，确保DOM已渲染
  setTimeout(() => {
    const scrollContainer = document.querySelector('.fishing-circle-content') as HTMLElement
    
    if (scrollContainer) {
      console.log('🎯 监听容器: .fishing-circle-content, 高度:', scrollContainer.clientHeight)
      scrollContainer.addEventListener('scroll', debouncedCheckLoadMore)
    } else {
      console.log('🎯 监听容器: document.body')
      document.body.addEventListener('scroll', debouncedCheckLoadMore)
    }
    
    console.log('✅ 滚动监听器已添加')

    // 初始检查
    console.log('🔍 执行初始检查...')
    checkLoadMore()
  }, 500)
})

onUnmounted(() => {
  cleanupListeners()
})
</script>
<style scoped>
/* 钓鱼圈专用容器 - 避免与MainContainer冲突 */
.fishing-circle-container {
  position: relative;
  width: 100%;
  height: 100vh;
  overflow: hidden;
  /* 确保不继承MainContainer的样式 */
  background: transparent;
}

.page-header {
  margin-bottom: 32px;
  text-align: center;
}

.page-title {
  font-size: 28px;
  font-weight: 700;
  color: var(--text-primary);
  margin: 0 0 8px 0;
}

.page-subtitle {
  font-size: 16px;
  color: var(--text-secondary);
  margin: 0;
}

/* 加载状态 */
.loading-container,
.error-container,
.empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: var(--text-secondary);
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid var(--border);
  border-top: 3px solid var(--accent-primary);
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

.loading-spinner.small {
  width: 20px;
  height: 20px;
  border-width: 2px;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

.error-icon,
.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.retry-btn {
  padding: 8px 16px;
  background: var(--bg-tertiary);
  color: var(--accent-primary);
  border: 1px solid var(--accent-primary);
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.retry-btn:hover {
  background: var(--bg-card);
  transform: translateY(-1px);
}

/* 内容区域 - 独立滚动 */
.fishing-circle-content {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100vh;
  overflow-y: auto;
  padding: 24px;
  padding-top: 80px; /* 为固定按钮留出空间 */
  box-sizing: border-box;
  background: var(--bg-primary);
  backdrop-filter: blur(12px);
}

.fishing-circle-content.scrollable {
  padding: 24px;
  padding-top: 80px; /* 保持顶部空间 */
}

.cards-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 24px;
  margin-bottom: 40px;
}

.circle-card {
  background: var(--bg-card);
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
}

.circle-card:hover {
  transform: translateY(-2px);
  background: var(--bg-tertiary);
}

.card-image {
  position: relative;
  width: 100%;
  height: 200px;
  overflow: hidden;
}

.card-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.circle-card:hover .card-image img {
  transform: scale(1.05);
}

.card-overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: linear-gradient(transparent, var(--bg-overlay));
  color: var(--text-primary);
  padding: 16px;
}

.status-badge {
  position: absolute;
  top: 12px;
  right: 12px;
  background: var(--bg-card);
  color: var(--text-primary);
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 600;
  transition: all 0.3s ease;
  backdrop-filter: blur(4px);
  z-index: 2;
}

.status-badge.active {
  background: var(--accent-primary);
  color: var(--text-inverse);
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  margin: 0 0 4px 0;
  color: var(--text-primary);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.card-city {
  font-size: 14px;
  margin: 0;
  color: var(--text-secondary);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 视图切换控制 - 固定定位在视窗右上角 */
.view-controls {
  position: fixed;
  top: 24px;
  right: 24px;
  z-index: 10001;
  pointer-events: auto;
}

.toggle-btn.single-toggle {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 18px;
  background: var(--bg-tertiary);
  backdrop-filter: blur(10px);
  border: 1px solid var(--border);
  border-radius: 8px;
  color: var(--text-primary);
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 14px;
  box-shadow: var(--shadow-card);
}

.toggle-btn.single-toggle:hover {
  background: var(--bg-card);
  color: var(--text-primary);
  transform: translateY(-1px);
}

.toggle-btn.single-toggle:active {
  transform: translateY(0);
}

.toggle-btn .icon {
  font-size: 16px;
}

/* 地图模式内容包装器 */
.map-content-wrapper {
  display: none;
}

/* 加载状态 */
.loading-more {
  text-align: center;
  color: var(--text-secondary);
  padding: 20px;
  font-size: 14px;
}

.end-message {
  text-align: center;
  color: var(--text-secondary);
  padding: 20px;
  font-size: 14px;
}

.scroll-trigger {
  cursor: pointer;
  transition: opacity 0.3s ease;
}

.scroll-trigger:hover {
  opacity: 0.8;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .fishing-circle-container {
    padding: 16px;
  }

  .page-title {
    font-size: 24px;
  }

  .cards-grid {
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
    gap: 16px;
  }

  .card-image {
    height: 180px;
  }
}

@media (max-width: 480px) {
  .fishing-circle-container {
    padding: 12px;
  }

  .cards-grid {
    grid-template-columns: 1fr;
    gap: 12px;
  }

  .card-image {
    height: 160px;
  }
}
</style>